var turnplate = {
    restaraunts: [],
    colors: [],
    outsideRadius: 190,
    textRadius: 155,
    insideRadius: 10,
    startAngle: 0,
    bRotate: false,
    allClickNum: 3,
    titleArr: [],
    coverObjInfo: null,
    lotteryRewardId: 0,
    randomitem: 0,
    dzpImg: [],
    haveClickNum: 1,
    alertMsg: "",
    locationSearch: window.location.search.substr(1),
    userId: 0,
    idArr: [],
    requestSearchObj: {},
    lotteryId: 0,
    lotteryWinType: 0,
    lotteryWinId: 0,
    contentBox: ".contentBox",
    remainCount: 3,
    timer: null,
    lgUrl: "",
    targetItem: 0,
    requestStyle: "",
    ttsTopFLoatObj: {},
    adUrl: "",
    detaiAdlUrl: ""
};
turnplate.requestStyle = document.location.protocol;
var newSearchObj = {
    pid: "",
    materialId: "",
    adTag: "",
    appKey: ""
};
if (turnplate.locationSearch != "") {
    var locationSearchObj = decodeURIComponent(turnplate.locationSearch),
    searchObjArr = locationSearchObj.split("&");
    console.log(locationSearchObj);
    for (var i = 0; i < searchObjArr.length; i++) {
        if (searchObjArr[i].indexOf("pid") > -1) {
            newSearchObj.pid = searchObjArr[i].split("=")[1]
        }
        if (searchObjArr[i].indexOf("materialId") > -1) {
            newSearchObj.materialId = searchObjArr[i].split("=")[1]
        }
        if (searchObjArr[i].indexOf("adTag") > -1) {
            newSearchObj.adTag = searchObjArr[i].split("=")[1]
        }
        if (searchObjArr[i].indexOf("appKey") > -1) {
            newSearchObj.appKey = searchObjArr[i].split("=")[1]
        }
    }
    var preSearchStr = " {pid:" + newSearchObj.pid + ",materialId:" + newSearchObj.materialId + "}";
    var newSearchStr = "ADTAG=" + newSearchObj.adTag + "&data=" + encodeURIComponent(preSearchStr) + "&appKey=" + newSearchObj.appKey;
    console.log(newSearchStr);
    if (location.hostname == "gamepre.adbaitai.com") {
        var mainHostName = "//gamepre.adbaitai.com";
        var btmUrlOne = mainHostName + "/api/1.0/h5/lottery/getLottery?" + newSearchStr;
        var btmUrlTwo = mainHostName + "/api/1.0/h5/lottery/gain?" + newSearchStr;
        var btmUrlThree = mainHostName + "/api/1.0/h5/lottery/rewardClick?"
    } else {
        if (location.hostname == "game.adbaitai.com") {
            var mainHostName = "//game.adbaitai.com";
            var btmUrlOne = mainHostName + "/api/1.0/h5/lottery/getLottery?" + newSearchStr;
            var btmUrlTwo = mainHostName + "/api/1.0/h5/lottery/gain?" + newSearchStr;
            var btmUrlThree = mainHostName + "/api/1.0/h5/lottery/rewardClick?"
        } else {
            if (location.hostname == "localhost") {
                var mainHostName = "//gamepre.adbaitai.com";
                var btmUrlOne = mainHostName + "/api/1.0/h5/lottery/getLottery?" + newSearchStr;
                var btmUrlTwo = mainHostName + "/api/1.0/h5/lottery/gain?" + newSearchStr;
                var btmUrlThree = mainHostName + "/api/1.0/h5/lottery/rewardClick?"
            }
        }
    }
}
$.ajax({
    url: btmUrlOne,
    dataType: "json",
    async: false,
    success: function(data) {
        if (data.msg) {
            alert(data.msg);
            return
        }
        data = JSON.parse(data);
        if (data.data.score != undefined) {
            turnplate.ttsTopFLoatObj = {
                score: data.data.score
            }
        }
        turnplate.remainCount = data.data.remain;
        $("title").html(data.data.lottery.title);
        if (data["success"]) {
            var allData = data["data"]["lottery"]["lotteryRewardVOs"],
            titleArr = allData.map(function(item) {
                return item.title
            });
            turnplate.idArr = allData.map(function(item) {
                return item.id
            });
            turnplate.titleArr = titleArr;
            turnplate.dzpImg = allData.map(function(item) {
                if (item.iconUrl) {
                    return item.iconUrl
                } else {
                    return "none"
                }
            });
            turnplate.restaraunts = titleArr;
            turnplate.allClickNum = data.data.remain
        }
    }
});
$(document).ready(function() {
    $("#allClickNum").html(turnplate.allClickNum);
    var hideImgObj = {
        "lists": turnplate.dzpImg
    };
    var hiddenImgObj = template("hiddenImgTemp", hideImgObj);
    $("#hiddenImg").html(hiddenImgObj);
    turnplate.colors = ["#fff4d6", "#ffc937", "#fff4d6", "#ffc937", "#fff4d6", "#ffc937"];
    var rotateTimeOut = function() {
        $("#wheelcanvas").rotate({
            angle: 0,
            animateTo: 2160,
            duration: 8000,
            callback: function() {
                alert("网络超时，请检查您的网络设置！")
            }
        })
    };
    var rotateFn = function(item, txt) {
        var angles = item * (360 / turnplate.restaraunts.length) - (360 / (turnplate.restaraunts.length * 2));
        if (angles < 270) {
            angles = 270 - angles
        } else {
            angles = 360 - angles + 270
        }
        $("#wheelcanvas").stopRotate();
        $("#wheelcanvas").rotate({
            angle: 0,
            animateTo: angles + 720,
            duration: 4000,
            callback: function() {
                $(".cover").css("display", "block");
                $(turnplate.contentBox).css("display", "block");
                turnplate.bRotate = !turnplate.bRotate
            }
        })
    };
    $("#dzpBtn").on("click",
    function() {
        if (turnplate.haveClickNum == 0) {
            $("#stcover").css("display", "block");
            return
        }
        if (turnplate.timer != null) {
            clearTimeout(turnplate.timer);
            turnplate.timer = null
        }
        MtaH5.clickStat("dzpgameclick");
        $("#wheelcanvas").removeClass("canvasRotate");
        if (turnplate.bRotate) {
            if (turnplate.alertMsg) {
                alert(turnplate.alertMsg)
            } else {
                return
            }
            return
        }
        turnplate.bRotate = !turnplate.bRotate;
        $.ajax({
            url: btmUrlTwo,
            dataType: "json",
            async: false,
            success: function(data) {
                if (data["success"] == undefined) {
                    if (JSON.parse(data)["success"]) {
                        turnplate.coverObjInfo = data;
                        var newDateObj = JSON.parse(data);
                        if (newDateObj.data.score != undefined) {
                            console.log(newDateObj.data.score);
                            console.log($("#scoreTotle"));
                            $("#scoreTotle").html(newDateObj.data.score);
                        }
                        turnplate.remainCount = newDateObj.data.remainCount;
                        if (newDateObj.data.lgUrl) {
                            turnplate.lgUrl = newDateObj.data.lgUrl
                        }
                        turnplate.lotteryId = newDateObj["data"]["lottery"]["lotteryId"];
                        turnplate.lotteryRewardId = newDateObj["data"]["lottery"]["lotteryRewardId"];
                        turnplate.lotteryWinType = newDateObj["data"]["lottery"]["lotteryRewardBizType"];
                        turnplate.lotteryWinId = newDateObj["data"]["lottery"]["winBizId"];
                        if (newDateObj["data"]["lottery"]["lotteryRewardBizType"] === 3) {
                            turnplate.adUrl = newDateObj.data.lottery.skipUrl;
                            var bizId = newDateObj.data.lottery.winBizId;
                            turnplate.detaiAdlUrl = "//adbaitai.com/dzp/gameDetail.html?winBizId=" + bizId;
                            turnplate.contentBox = ".contentBoxTwo";
                            var dateObjst = new Date(newDateObj["data"]["lottery"]["endValid"]),
                            yearObj = dateObjst.getFullYear(),
                            monthObj = dateObjst.getMonth() + 1,
                            dayObj = dateObjst.getDate(),
                            newDateObjst = yearObj + "-" + monthObj + "-" + dayObj;
                            newDateObj["data"]["lottery"]["endValid"] = newDateObjst;
                            var obj = template("coverOtherTemplate", newDateObj["data"])
                        }else if(newDateObj["data"]["lottery"]["lotteryRewardBizType"] === 5){
                          turnplate.contentBox = ".contenthb";
                          var obj = template("freeTemplate", newDateObj["data"]);
                        }else {
                            if (newDateObj["data"]["lottery"]["lotteryRewardBizType"] === 4) {
                                turnplate.contentBox = ".contenthb";
                                var obj = template("hbTemplate", newDateObj["data"])
                            } else {
                                if (newDateObj["data"]["lottery"]["lotteryRewardBizType"] === 0) {
                                    turnplate.contentBox = ".contentBox";
                                    var obj = template("coverTemplate", newDateObj["data"])
                                }
                            }
                        }
                        $("#stcover").html(obj);
                        var stbtmnum = parseInt(JSON.parse(data)["data"]["remainCount"]);
                        $("#allClickNum").text(stbtmnum);
                        var backId = turnplate.lotteryRewardId;
                        var item;
                        for (var i = 0; i < turnplate.idArr.length; i++) {
                            if (turnplate.idArr[i] == backId) {
                                item = i + 1
                            }
                        }
                        turnplate.targetItem = item;
                        rotateFn(item, turnplate.restaraunts[item - 1])
                    }
                } else {
                    if (data["msg"]) {
                        if (data["code"] == 1103) {
                            turnplate.contentBox = ".contentBoxThreee";
                            turnplate.haveClickNum = 0;
                            var stObj = template("noFrequencyTemp", data);
                            $(".cover").css("display", "block");
                            $("#stcover").html(stObj)
                        } else {
                            turnplate.alertMsg = data["msg"];
                            alert(data["msg"])
                        }
                    }
                }
            }
        })
    })
});
window.onload = function() {
    drawRouletteWheel();
    var topFloatObj = template("topFloatTemplte", turnplate.ttsTopFLoatObj);
    $(document.body).append(topFloatObj)
};
function drawRouletteWheel() {
    var canvas = document.getElementById("wheelcanvas");
    if (canvas.getContext) {
        var arc = Math.PI / (turnplate.restaraunts.length / 2);
        var ctx = canvas.getContext("2d");
        ctx.clearRect(0, 0, 422, 422);
        ctx.scale(2, 2);
        ctx.strokeStyle = "#FFBE04";
        ctx.font = "bold 15px Microsoft YaHei";
        for (var i = 0; i < turnplate.restaraunts.length; i++) {
            var angle = turnplate.startAngle + i * arc;
            ctx.fillStyle = turnplate.colors[i];
            ctx.beginPath();
            ctx.arc(211, 211, turnplate.outsideRadius - 10, angle, angle + arc, false);
            ctx.arc(211, 211, turnplate.insideRadius + 10, angle + arc, angle, true);
            ctx.stroke();
            ctx.fill();
            ctx.save();
            ctx.fillStyle = "#E5302F";
            var text = turnplate.restaraunts[i];
            var line_height = 15;
            if (text.indexOf("元") > 0) {
                ctx.fillStyle = "#846af4"
            } else {
                ctx.fillStyle = "#E5302F"
            }
            ctx.translate(211 + Math.cos(angle + arc / 2) * turnplate.textRadius, 211 + Math.sin(angle + arc / 2) * turnplate.textRadius);
            ctx.rotate(angle + arc / 2 + Math.PI / 2);
            if (turnplate.dzpImg[i] == "none") {
                if (text.indexOf("谢谢") > -1) {
                    var num = i + 1;
                    var img = document.getElementById("thanksImg");
                    img.onload = function() {
                        ctx.drawImage(img, -15, 10)
                    };
                    ctx.drawImage(img, -33, 0, 66, 73)
                } else {
                    if (turnplate.titleArr[i].length > 2 && turnplate.titleArr[i].length <= 4) {
                        showText(ctx, 2, i, line_height)
                    } else {
                        if (turnplate.titleArr[i].length > 4 && turnplate.titleArr[i].length <= 6) {
                            showText(ctx, 3, i, line_height)
                        } else {
                            if (turnplate.titleArr[i].length > 6 && turnplate.titleArr[i].length <= 8) {
                                showText(ctx, 4, i, line_height)
                            } else {
                                ctx.fillText(text, -ctx.measureText(text).width / 2, 0)
                            }
                        }
                    }
                }
            } else {
                ctx.fillText(text, -ctx.measureText(text).width / 2, 5)
            }
            if (turnplate.dzpImg[i] != "none") {
                var num = i + 1;
                var img = document.getElementById("btm" + num);
                img.onload = function() {
                    ctx.drawImage(img, -15, 10)
                };
                ctx.drawImage(img, -33, 7, 70, 70)
            }
            ctx.restore()
        }
    }
}
function closeCover(type) {
    $("#wheelcanvas").rotate({
        angle: 0,
        animateTo: 7200,
        duration: 1200000,
        callback: function() {}
    });
    if (type === 1) {
        MtaH5.clickStat("dzpgamejump");
        var newRequestSearchStr = cancatSearchStr(turnplate.locationSearch);
        $.ajax({
            url: btmUrlThree + newRequestSearchStr,
            success: function(data) {
                console.log(data)
            }
        })
    } else {
        if (type === 2) {
            MtaH5.clickStat("jumptolg");
            var newRequestSearchStr = cancatSearchStr(turnplate.locationSearch);
            console.log(newRequestSearchStr);
            $.ajax({
                url: btmUrlThree + newRequestSearchStr,
                success: function(data) {
                    console.log(data)
                }
            })
        } else {
            if (type === 6) {
                var lgUrlObj = {
                    attribute: {
                        lgUrl: turnplate.lgUrl
                    }
                };
                if (turnplate.remainCount == 0) {
                    turnplate.timer = setTimeout(function() {
                        turnplate.contentBox = ".contentBoxThreee";
                        turnplate.haveClickNum = 0;
                        var stObj = template("noFrequencyTemp", lgUrlObj);
                        $(".cover").css("display", "block");
                        $("#stcover").html(stObj)
                    },
                    3000)
                }
            } else {
                if (type == 11) {
                    window.location.href = turnplate.adUrl;
                    var newRequestSearchStr = cancatSearchStr(turnplate.locationSearch);
                    $.ajax({
                        url: btmUrlThree + newRequestSearchStr,
                        success: function(data) {
                            console.log(data)
                        }
                    })
                } else {
                    if (type == 12) {
                        window.location.href = turnplate.detaiAdlUrl
                    }
                }
            }
        }
    }
    $(".cover").css("display", "none")
}
function showText(ctx, dot, index, line_height) {
    var preStr = turnplate.titleArr[index].slice(0, dot),
    nextStr = turnplate.titleArr[index].slice(dot);
    newArr = [];
    newArr[0] = preStr;
    newArr[1] = nextStr;
    for (var j = 0; j < newArr.length; j++) {
        ctx.font = "bold 25px Microsoft YaHei";
        if (j == 0) {
            ctx.fillText(newArr[j] + "", -ctx.measureText(newArr[j] + "M").width / 3, j * line_height * 3 + 20)
        } else {
            ctx.fillText(newArr[j], -ctx.measureText(newArr[j]).width / 2, j * line_height * 2 + 20)
        }
    }
}
function goBack() {
    if (window.history.length > 0) {
        window.history.go( - 1)
    } else {
        $("#goBack").css("display", "none")
    }
}
function cancatSearchStr(obj) {
    console.log(obj);
    var newArr = obj.split("&"),
    newArrObj = {};
    for (var i = 0; i < newArr.length; i++) {
        if (newArr[i].indexOf("pid") > -1) {
            newArrObj.pid = newArr[i].split("=")[1]
        }
        if (newArr[i].indexOf("materialId") > -1) {
            newArrObj.materialId = newArr[i].split("=")[1]
        }
        if (newArr[i].indexOf("appKey") > -1) {
            newArrObj.appKey = newArr[i].split("=")[1]
        }
    }
    var newStr = "";
    newStr += "data=%7bpid:";
    newStr += newArrObj.pid;
    newStr += ",lotteryId:";
    newStr += turnplate.lotteryId;
    newStr += ",lotteryWinType:";
    newStr += turnplate.lotteryWinType;
    newStr += ",lotteryWinId:";
    newStr += turnplate.lotteryWinId;
    newStr += ",materialId:";
    newStr += newArrObj.materialId;
    newStr += "%7d";
    newStr += "&appKey=";
    newStr += newArrObj.appKey;
    console.log(newStr);
    return newStr
};
